package com.road.vast.springboot.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.road.vast.springboot.project.mapper.*;
import com.road.vast.springboot.project.pojo.PeRolePermission;
import com.road.vast.springboot.project.pojo.PeUser;
import com.road.vast.springboot.project.pojo.PeUserRole;
import com.road.vast.springboot.project.service.PeUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 郭泽鹏
 * @since 2020-08-01
 */
@Service
public class PeUserServiceImpl extends ServiceImpl<PeUserMapper, PeUser> implements PeUserService {
    @Resource
    PeUserMapper userMapper;

    @Resource
    PeUserRoleMapper userRoleMapper;

    @Resource
    PeRolePermissionMapper rolePermissionMapper;

    @Resource
    PeRoleMapper roleMapper;

    @Resource
    PePermissionMapper permissionMapper;

    @Override
    public PeUser findByName(String username) {
        QueryWrapper<PeUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        PeUser user = userMapper.selectOne(wrapper);
        return user;
    }

    @Override
    public Map<String, Object> getRolesAndPermissionByUserId(String userId) {
        Map<String, Object> map = new HashMap<>();
        Set<String> roleNames = new HashSet<>();
        Set<String> permCodes = new HashSet<>();

        //通过用户id获取对应的角色
        QueryWrapper<PeUserRole> userRoleWrapper = new QueryWrapper<>();
        userRoleWrapper.eq("user_id", userId);
        List<PeUserRole> userRoles = userRoleMapper.selectList(userRoleWrapper);
        //通过角色获取对应的权限
        for (PeUserRole userRole : userRoles) {
            roleNames.add(roleMapper.selectById(userRole.getRoleId()).getName());
            QueryWrapper<PeRolePermission> rolePermissionWrapper = new QueryWrapper<>();
            userRoleWrapper.eq("role_id", userRole.getRoleId());
            List<PeRolePermission> rolePermissions = rolePermissionMapper.selectList(rolePermissionWrapper);
            for (PeRolePermission rolePermission : rolePermissions) {
                permCodes.add(permissionMapper.selectById(rolePermission.getPermissionId()).getCode());
            }
        }
        map.put("roleNames", roleNames);
        map.put("permCodes", permCodes);

        return map;
    }
}
